package com.cah.game;
import org.json.JSONException;
import org.json.JSONObject;

import com.cah.library.UserFunctions;

import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class GameFragment extends Fragment
{
	String gameKey, userKey;
	FragmentManager fragmentManager;
	MainActivity main;

	private static final String GAME_INFO_FRAGMENT_TAG = "gameInfo";
	private static final int GAME_INFO_FRAGMENT = 1;
	
	public GameFragment(String gk)
	{
		super();
		gameKey = gk;
	}
	
	public GameFragment()
	{
		super();
		gameKey = "";
	}
	
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		fragmentManager = getFragmentManager();
		RedirectFragment rf = (RedirectFragment)fragmentManager.findFragmentByTag(GAME_INFO_FRAGMENT_TAG);
		
		if(rf != null)
		{
			rf.setTargetFragment(this, GAME_INFO_FRAGMENT);
		}
		else
		{
			rf = new RedirectFragment();
			rf.setTask(new RedirectProcess());
			rf.setTargetFragment(this, GAME_INFO_FRAGMENT);
			rf.show(fragmentManager, GAME_INFO_FRAGMENT_TAG);
		}
	}
	
	public void onActivityCreated(Bundle savedInstanceState)
	{
		super.onActivityCreated(savedInstanceState);
		main = (MainActivity)getActivity();
		userKey = main.getUserKey();
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if((requestCode == GAME_INFO_FRAGMENT) && (resultCode == Activity.RESULT_OK))
		{
			try
			{
				JSONObject json = new JSONObject(data.getStringExtra("gameInfo"));
				if(json.getInt("success")==1)
				{
					JSONObject gameInfo = json.getJSONObject("value");
					boolean userIsCzar = gameInfo.getBoolean("userIsCzar");
					
					if(userIsCzar)
					{
						main.startGameCzarFragment(gameKey, gameInfo);
					}
					else
					{
						main.startGameNotCzarFragment(gameKey, gameInfo);
					}
				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
		}
	}
	
	private class RedirectFragment extends DialogFragment
	{
		RedirectProcess task;
		
		public void setTask(RedirectProcess t)
		{
			task = t;
			t.setFragment(this);
		}
		
		@Override
		public void onCreate(Bundle savedInstanceState)
		{
			super.onCreate(savedInstanceState);
			
			setRetainInstance(true);
			
			if(task != null)
			{
				task.execute(gameKey);
			}
		}
		
		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState)
		{
			ProgressDialog pdia = new ProgressDialog(main);
			pdia.setMessage("Loading your game...");
			pdia.setCanceledOnTouchOutside(false);
			return pdia;
		}
		
		@Override
        public void onDestroyView()
        {
            if (getDialog() != null && getRetainInstance())
                getDialog().setDismissMessage(null);
            super.onDestroyView();
        }
		
		@Override
        public void onDismiss(DialogInterface dialog)
        {
            super.onDismiss(dialog);
            // If true, the thread is interrupted immediately, which may do bad things.
            // If false, it guarantees a result is never returned (onPostExecute() isn't called)
            // but you have to repeatedly call isCancelled() in your doInBackground()
            // function to check if it should exit. For some tasks that might not be feasible.
            if (task != null) {
                task.cancel(false);
            }
        }
		
		@Override
        public void onResume()
        {
            super.onResume();
            // This is a little hacky, but we will see if the task has finished while we weren't
            // in this activity, and then we can dismiss ourselves.
            if (task == null)
                dismiss();
        }
		
		public void taskFinished(JSONObject json)
		{
			// Make sure we check if it is resumed because we will crash if trying to dismiss the dialog
            // after the user has switched to another app.
            if (isResumed())
                dismiss();

            // If we aren't resumed, setting the task to null will allow us to dimiss ourselves in
            // onResume().
            task = null;

            // Tell the fragment that we are done.
            if (getTargetFragment() != null)
            {
            	Intent data = new Intent();
            	Log.e("json", json.toString());
            	data.putExtra("gameInfo", json.toString());
            	getTargetFragment().onActivityResult(GAME_INFO_FRAGMENT, Activity.RESULT_OK, data);
            }
		}
		
	}
	
	private class RedirectProcess extends AsyncTask<String, Void, JSONObject>
	{
		String gameKey;
		RedirectFragment frag;
		
		void setFragment(RedirectFragment f)
		{
			frag = f;
		}
				
		@Override
		protected JSONObject doInBackground(String... params)
		{
			gameKey = params[0];
			UserFunctions uf = new UserFunctions(userKey);
			return uf.fetchGameInfo(gameKey);
		}
		
		protected void onPostExecute(JSONObject json)
		{
			if(frag==null)
			{
				return;
			}
			
			frag.taskFinished(json);
		}
	}
}
